<?php
class Controller_Admin_Login extends FLEA_Controller_Action{
	private $_ModelSysRoles;
	private $_ModelSysUsers;
	private $siteInfo;
	
	function Controller_Admin_Login(){
		$this->siteInfo = FLEA::getAppInf('siteInfo');
		$this->_ModelSysRoles = & FLEA::getSingleton('Model_SysRoles');
		$this->_ModelSysUsers = & FLEA::getSingleton('Model_SysUsers');
		$this->_ModelSysUsers -> encodeMethod = PWD_MD5;
	}
	
	function actionIndex(){
		$viewData = array(
			'siteInfo' => $this -> siteInfo,
		);
		$this->_executeView('Admin_Login_Index.html',$viewData);
	}
	
	function actionLogin(){
		$username = addslashes(trim($_POST['username']));
		$password = addslashes($_POST['password']);

		do {
			$sysusers =& FLEA::getSingleton('Model_SysUsers');//instantiate user class
			$sysusers -> encodeMethod = PWD_MD5;//set encode
			$user = $sysusers->findByUsername($username);//check user is or isn't existence

			/*
			 * check user
			 */
			if (!$user) {
				$msg = '用户名不存在';//point user isn't existence
				js_alert($msg,'',url('Admin_Login'));
			}

			/*
			 * check password
			 */
			if (!$sysusers->checkPassword($password,$user[$sysusers->passwordField])){
				$msg = '密码错误';//point password wrong
				js_alert($msg,'',url('Admin_Login'));
			}

			/*
			 * save user information
			 */
			$data = array();
			if(isset($user[$sysusers->usernameField])&&!empty($user[$sysusers->usernameField])){
				$data['USERNAME'] = $user[$sysusers->usernameField];
				$data['ID'] = $user[$sysusers->primaryKey];
			}else{
				$data['USERNAME'] = $email[$sysusers->usernameField];
				$data['ID'] = $email[$sysusers->primaryKey];
			}

			$sysusers -> functionFields = FLEA::getAppInf('functionFields');//include user table fields
			$sysusers -> validateUser($username,$password);//update user login data

			$rbac =& FLEA::getSingleton('FLEA_Rbac');
			$rbac->setUser($data, $sysusers->fetchRoles($user));

			redirect(url('Admin_Default','Index'));

		}while(false);

		redirect(url('Admin_Login'));
	}

	function actionLogout(){
		session_destroy();
		redirect(url('Admin_Login'));
	}
}
?>